using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Threading.Tasks;

namespace Woodlands
{
    /// <summary>
    /// Interaction logic for StudentWindow.xaml
    /// </summary>
    public partial class StudentWindow : Page
    {

        public StudentWindow()
        {
            InitializeComponent();
            DataTable courseTable = new DataTable();
            Database.fillCourse().Fill(courseTable);
            courseBox.DataContext = courseTable;
            courseBoxAmend.DataContext = courseTable;
            courseBox.SelectedIndex = 0;
            courseBoxAmend.SelectedIndex = 0;
            createStudentIDTxt.Text = Student.nextID();
        }

        private async void name_KeyUp(object sender, KeyEventArgs e)
        {
            if (createStudentFNameTxt.Text.Length > 0 && createStudentLastNameTxt.Text.Length > 0)
            {
                string test = await Database.newEmail(createStudentFNameTxt.Text, createStudentLastNameTxt.Text) + "@woodlandsuniversity.com";
                if (test != "")
                {
                    createStudentWUCEmailTxt.Text = test;
                }
            }
            else
            {
                createStudentWUCEmailTxt.Text = "";
            }
        }

        private async void create_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Visibility hidden = System.Windows.Visibility.Hidden;
            System.Windows.Visibility visible = System.Windows.Visibility.Visible;
            createFirstnameError.Visibility = hidden;
            createLastnameError.Visibility = hidden;
            createDOBError.Visibility = hidden;
            createLine1Error.Visibility = hidden;
            createCityError.Visibility = hidden;
            createPostCodeError.Visibility = hidden;
            createPhoneError.Visibility = hidden;
            bool error = false;
            if (createStudentFNameTxt.Text.Length == 0)
            {
                error = true;
                createFirstnameError.Visibility = visible;
            }
            if (createStudentLastNameTxt.Text.Length == 0)
            {
                error = true;
                createLastnameError.Visibility = visible;
            }
            if (createStudentDOBTxt.Text.Length == 0)
            {
                error = true;
                createDOBError.Visibility = visible;
            }
            if (createStudentTTLine1Txt.Text.Length == 0)
            {
                error = true;
                createLine1Error.Visibility = visible;
            }
            if (createStudentTTCityTxt.Text.Length == 0)
            {
                error = true;
                createCityError.Visibility = visible;
            }
            if (createStudentTTPostcodeTxt.Text.Length == 0)
            {
                error = true;
                createPostCodeError.Visibility = visible;
            }
            if (createStudentHomeNoTxt.Text.Length == 0)
            {
                error = true;
                createPhoneError.Visibility = visible;
            }
            if (error)
            {
                return;
            }

            string email = createStudentWUCEmailTxt.Text;
            string password = createStudentFNameTxt.Text.ToLower()[0] + createStudentLastNameTxt.Text.ToLower() + createStudentDOBTxt.Text.Substring(0, 4) + "=";
            save.Content = "Saving...";
            save.IsEnabled = false;
            Student student = new Student();
            student.ID = createStudentIDTxt.Text;
            student.FirstName = createStudentFNameTxt.Text;
            student.MiddleName = createStudentMNameTxt.Text;
            student.LastName = createStudentLastNameTxt.Text;
            student.HomePhone = createStudentHomeNoTxt.Text;
            student.MobilePhone = createStudentMobNoTxt.Text;
            student.EmailUni = email + "@woodlandsuniversity.com";
            student.EmailPersonal = createStudentEmailTxt.Text;
            student.tLine1 = createStudentTTLine1Txt.Text;
            student.tLine2 = createStudentTTLine2Txt.Text;
            student.tCity = createStudentTTCityTxt.Text;
            student.tPostCode = createStudentTTPostcodeTxt.Text;
            student.hLine1 = createStudentNTTLine1Txt.Text;
            student.hLine2 = createStudentNTTLine2Txt.Text;
            student.hCity = createStudentNTTCityTxt.Text;
            student.hPostCode = createStudentNTTPostcodeTxt.Text;
            student.CourseID = Convert.ToInt32(courseBox.SelectedValue.ToString());
            student.DOB = createStudentDOBTxt.Text;

            
            //await Mail.addMailBox(email, password); //mailbox has been disabled while i deal with load times
            FileSpace.createFileSpace(student.ID);
            await student.create();
            createStudentIDTxt.Text = Student.nextID();
            if (student.MobilePhone != "")
            {
                string number = "";
                int count = 0;
                foreach (char a in student.MobilePhone.ToCharArray())
                {
                    if (a == 0 && count == 0)
                    {
                        number += 44;
                        count++;
                        continue;
                    }
                    number += a;
                }
                string message = student.FirstName + " " + student.LastName + " you have been provisionally enroled on the course " + courseBox.Text + " Your StudentID is " + student.ID;
                Notification.sms(number, message);
            }
           
            foreach (TextBox child in FindVisualChildren<TextBox>(createGrid))
            {
                child.Text = string.Empty;
            }

            courseBox.SelectedIndex = 0;

            save.Content = "Save";
            save.IsEnabled = true;
            MessageBox.Show(student.FirstName + " has been provisional enrolled on " + courseBox.Text);
        }
        private async void displayEnrol()
        {
            if (studentIDTxtEnrol.Text.Length == 8)
            {
                Student student = await Student.search(studentIDTxtEnrol.Text);
                if (student.FirstName.Length == 0)
                {
                    fNameTxtEnrol.Text = "";
                    mNameTxtEnrol.Text = "";
                    surnameTxtEnrol.Text = "";
                    courseTxtEnrol.Text = "";
                    createStudentDOBTxt.Text = "";
                    currentStatusTxt.Text = "Invalid StudentID";
                }
                else
                {
                    fNameTxtEnrol.Text = student.FirstName;
                    mNameTxtEnrol.Text = student.MiddleName;
                    surnameTxtEnrol.Text = student.LastName;
                    createStudentDOBTxt.Text = student.DOB;
                    courseTxtEnrol.Text = student.CourseID.ToString();
                    currentStatusTxt.Text = student.Status;
                }
            }
            else if (studentIDTxtEnrol.Text.Length > 8)
            {
                fNameTxtEnrol.Text = "";
                mNameTxtEnrol.Text = "";
                surnameTxtEnrol.Text = "";
                courseTxtEnrol.Text = "";
                createStudentDOBTxt.Text = "";
                currentStatusTxt.Text = "A student ID must be 8 digits long";
            }
        }

        private void studentIDTxtEnrol_KeyUp(object sender, KeyEventArgs e)
        {
            displayEnrol();
        }

        private async void EnrolBtn_Click(object sender, RoutedEventArgs e)
        {
            EnrolBtn.Content = "Enrolling...";
            EnrolBtn.IsEnabled = false;
            if (currentStatusTxt.Text == "Provisional")
            {
                await Student.enrol(studentIDTxtEnrol.Text);
                Student student = await Student.search(studentIDTxtEnrol.Text);
                currentStatusTxt.Text = student.Status;
                if (student.MobilePhone != "")
                {
                    string number = "";
                    int count = 0;
                    foreach (char a in student.MobilePhone.ToCharArray())
                    {
                        if (a == 0 && count == 0)
                        {
                            number += 44;
                            count++;
                            continue;
                        }
                        number += a;
                    }
                    string message = student.FirstName + " " + student.LastName + " you have been enroled on your course at Woodlands University Colledge Your StudentID is " + student.ID;
                    Notification.sms(number, message);
                }
                EnrolBtn.Content = "Enrol";
                EnrolBtn.IsEnabled = true;
            }
            else if (currentStatusTxt.Text == "Invalid StudentID")
            {
                MessageBox.Show("The Student ID you have entered is not valid");
            }
            else if (currentStatusTxt.Text == "A student ID must be 8 digits long")
            {
                MessageBox.Show("The current Student ID is too long, it must only be 8 digits long");
            }
            else if (currentStatusTxt.Text == "")
            {
                MessageBox.Show("You must enter a complete Student ID");
            }
            else
            {
                MessageBox.Show("The Student must currently have Provisional Status");
            }
        }

        private void CancelEnrolBtn_Click(object sender, RoutedEventArgs e)
        {
            studentIDTxtEnrol.Text = "";
            fNameTxtEnrol.Text = "";
            mNameTxtEnrol.Text = "";
            surnameTxtEnrol.Text = "";
            courseTxtEnrol.Text = "";
            createStudentDOBTxt.Text = "";
            currentStatusTxt.Text = "";
        }

        private void dobTxt_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (createStudentDOBTxt.Text == "DD/MM/YYYY")
            {
                createStudentDOBTxt.Text = "";
            }
        }

        private void dobTxt_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (createStudentDOBTxt.Text == "")
            {
                createStudentDOBTxt.Text = "DD/MM/YYYY";
            }
        }

        private async void displayAmend()
        {
            if (studentIDTxtAmend.Text.Length == 8)
            {
                Student student = await Student.search(studentIDTxtAmend.Text);
                if (student.FirstName != "")
                {
                    fNameTxtAmend.Text = student.FirstName;
                    mNameTxtAmend.Text = student.MiddleName;
                    surnameTxtAmend.Text = student.LastName;
                    courseBoxAmend.SelectedIndex = 0;
                    textBox4Amend.Text = student.HomePhone;
                    textBox5Amend.Text = student.MobilePhone;
                    emailTxtAmend.Text = student.EmailPersonal;
                    ttLine1TxtAmend.Text = student.tLine1;
                    ttLine2TxtAmend.Text = student.tLine2;
                    ttCityTxtAmend.Text = student.tCity;
                    postcodeTxtAmend.Text = student.tPostCode;
                    nttLine1TxtAmend.Text = student.hLine1;
                    textBox2Amend.Text = student.hLine2;
                    textBoxAmend.Text = student.hCity;
                    textBox3Amend.Text = student.hPostCode;
                    if (student.Status == "Provisional")
                    {
                        Astatus.SelectedIndex = 0;
                    }
                    else if (student.Status == "Live")
                    {
                        Astatus.SelectedIndex = 1;
                    }
                    else if (student.Status == "Dormant")
                    {
                        Astatus.SelectedIndex = 2;
                    }
                    fNameTxtAmend.IsEnabled = true;
                    mNameTxtAmend.IsEnabled = true;
                    surnameTxtAmend.IsEnabled = true;
                    courseBoxAmend.IsEnabled = true;
                    textBox4Amend.IsEnabled = true;
                    textBox5Amend.IsEnabled = true;
                    emailTxtAmend.IsEnabled = true;
                    ttLine1TxtAmend.IsEnabled = true;
                    ttLine2TxtAmend.IsEnabled = true;
                    ttCityTxtAmend.IsEnabled = true;
                    postcodeTxtAmend.IsEnabled = true;
                    nttLine1TxtAmend.IsEnabled = true;
                    textBox2Amend.IsEnabled = true;
                    textBoxAmend.IsEnabled = true;
                    textBox3Amend.IsEnabled = true;
                    Astatus.IsEnabled = true;
                }
                else
                {
                    fNameTxtAmend.IsEnabled = false;
                    mNameTxtAmend.IsEnabled = false;
                    surnameTxtAmend.IsEnabled = false;
                    courseBoxAmend.IsEnabled = false;
                    textBox4Amend.IsEnabled = false;
                    textBox5Amend.IsEnabled = false;
                    emailTxtAmend.IsEnabled = false;
                    ttLine1TxtAmend.IsEnabled = false;
                    ttLine2TxtAmend.IsEnabled = false;
                    ttCityTxtAmend.IsEnabled = false;
                    postcodeTxtAmend.IsEnabled = false;
                    nttLine1TxtAmend.IsEnabled = false;
                    textBox2Amend.IsEnabled = false;
                    textBoxAmend.IsEnabled = false;
                    textBox3Amend.IsEnabled = false;
                    Astatus.IsEnabled = false;
                }
            }
            else
            {
                fNameTxtAmend.Text = "";
                mNameTxtAmend.Text = "";
                surnameTxtAmend.Text = "";
                courseBoxAmend.SelectedIndex = 0;
                textBox4Amend.Text = "";
                textBox5Amend.Text = "";
                emailTxtAmend.Text = "";
                ttLine1TxtAmend.Text = "";
                ttLine2TxtAmend.Text = "";
                ttCityTxtAmend.Text = "";
                postcodeTxtAmend.Text = "";
                nttLine1TxtAmend.Text = "";
                textBox2Amend.Text = "";
                textBoxAmend.Text = "";
                textBox3Amend.Text = "";
                fNameTxtAmend.IsEnabled = false;
                mNameTxtAmend.IsEnabled = false;
                surnameTxtAmend.IsEnabled = false;
                courseBoxAmend.IsEnabled = false;
                textBox4Amend.IsEnabled = false;
                textBox5Amend.IsEnabled = false;
                emailTxtAmend.IsEnabled = false;
                ttLine1TxtAmend.IsEnabled = false;
                ttLine2TxtAmend.IsEnabled = false;
                ttCityTxtAmend.IsEnabled = false;
                postcodeTxtAmend.IsEnabled = false;
                nttLine1TxtAmend.IsEnabled = false;
                textBox2Amend.IsEnabled = false;
                textBoxAmend.IsEnabled = false;
                textBox3Amend.IsEnabled = false;
                Astatus.IsEnabled = false;
            }
        }

        private void studentIDTxtAmend_KeyUp(object sender, KeyEventArgs e)
        {
            displayAmend();
        }

        private async void displayArchive()
        {
            if (studentIDTxtArchive.Text.Length == 8)
            {
                Student student = await Student.search(studentIDTxtArchive.Text);
                if (student.FirstName.Length == 0)
                {
                    fNameTxtArchive.Text = "";
                    mNameTxtArchive.Text = "";
                    surnameTxtArchive.Text = "";
                    courseTxtArchive.Text = "";
                    dobTxtArchive.Text = "";
                    currentStatusTxtArchive.Text = "Invalid StudentID";
                }
                else
                {
                    fNameTxtArchive.Text = student.FirstName;
                    mNameTxtArchive.Text = student.MiddleName;
                    surnameTxtArchive.Text = student.LastName;
                    dobTxtArchive.Text = student.DOB;
                    courseTxtArchive.Text = student.CourseID.ToString();
                    currentStatusTxtArchive.Text = student.Status;
                }
            }
            else if (studentIDTxtEnrol.Text.Length > 8)
            {
                fNameTxtArchive.Text = "";
                mNameTxtArchive.Text = "";
                surnameTxtArchive.Text = "";
                courseTxtArchive.Text = "";
                createStudentDOBTxt.Text = "";
                currentStatusTxt.Text = "A student ID must be 8 digits long";
            }
        }

        private void studentIDTxtArchive_KeyUp(object sender, KeyEventArgs e)
        {
            displayArchive();
        }

        private async void BtnArchive_Click(object sender, RoutedEventArgs e)
        {
            if (currentStatusTxtArchive.Text == "Live" || currentStatusTxtArchive.Text == "Provisional")
            {
                Student.archive(studentIDTxtArchive.Text);
                Student student = await Student.search(studentIDTxtArchive.Text);
                currentStatusTxtArchive.Text = student.Status;
            }
            else if (currentStatusTxtArchive.Text == "Invalid StudentID")
            {
                MessageBox.Show("The Student ID you have entered is not valid");
            }
            else if (currentStatusTxtArchive.Text == "A student ID must be 8 digits long")
            {
                MessageBox.Show("The current Student ID is too long, it must only be 8 digits long");
            }
            else if (currentStatusTxtArchive.Text == "")
            {
                MessageBox.Show("You must enter a complete Student ID");
            }
            else
            {
                MessageBox.Show("The Student must currently have Provisional or Live Status");
            }
        }

        private void CancelBtnArchive_Click(object sender, RoutedEventArgs e)
        {
            studentIDTxtArchive.Text = "";
            fNameTxtArchive.Text = "";
            mNameTxtArchive.Text = "";
            surnameTxtArchive.Text = "";
            courseTxtArchive.Text = "";
            dobTxtArchive.Text = "";
            currentStatusTxtArchive.Text = "";
        }

        private async void studentSearch_KeyUp(object sender, KeyEventArgs e)
        {

            resultsBox.Items.Clear();
            if (studentSearch.Text.Length >= 3)
            {
                searchLoading.Visibility = Visibility.Visible;
                DataTable table = await Student.search(searchType.Text, studentSearch.Text);
                resultsBox.Items.Add("Student ID\tFirstname\tLastname\tDOB\t\tstatus");
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    string data1 = table.Rows[i]["userID"].ToString() + "\t" + table.Rows[i]["firstname"].ToString() + "\t\t" + table.Rows[i]["lastname"].ToString() + "\t\t" + table.Rows[i]["DOB"].ToString() + "\t" + table.Rows[i]["status"].ToString();
                    resultsBox.Items.Add(data1);
                }
                searchLoading.Visibility = Visibility.Hidden;
            }
            
        }
        public string DialogValue = "";
        private void resultsBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (resultsBox.SelectedValue != null && resultsBox.SelectedIndex != 0)
            {
                DialogBox dialog = new DialogBox(this);
                dialog.ShowDialog();
                if (DialogValue == "amend")
                {
                    studentIDTxtAmend.Text = resultsBox.SelectedValue.ToString().Substring(0, 8);
                    displayAmend();
                    subMenu.SelectedIndex = 1;
                }
                else if (DialogValue == "enrol")
                {
                    studentIDTxtEnrol.Text = resultsBox.SelectedValue.ToString().Substring(0, 8);
                    displayEnrol();
                    subMenu.SelectedIndex = 3;
                }
                else if (DialogValue == "archive")
                {
                    studentIDTxtArchive.Text = resultsBox.SelectedValue.ToString().Substring(0, 8);
                    displayArchive();
                    subMenu.SelectedIndex = 2;
                }
                else
                {
                    resultsBox.SelectedItem = null;
                }
                DialogValue = "";
            }
        }
        public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }

        private void tab_GotFocus(object sender, RoutedEventArgs e)
        {
            if (e.Source == create || e.Source == amend || e.Source == archive || e.Source == search || e.Source == enrol)
            {
                foreach (TextBox child in FindVisualChildren<TextBox>(amendGrid))
                {
                    child.Text = string.Empty;
                }
            }
        }

        private void disableAmend()
        {
            fNameTxtAmend.IsEnabled = false;
            mNameTxtAmend.IsEnabled = false;
            surnameTxtAmend.IsEnabled = false;
            courseBoxAmend.IsEnabled = false;
            textBox4Amend.IsEnabled = false;
            textBox5Amend.IsEnabled = false;
            emailTxtAmend.IsEnabled = false;
            ttLine1TxtAmend.IsEnabled = false;
            ttLine2TxtAmend.IsEnabled = false;
            ttCityTxtAmend.IsEnabled = false;
            postcodeTxtAmend.IsEnabled = false;
            nttLine1TxtAmend.IsEnabled = false;
            textBox2Amend.IsEnabled = false;
            textBoxAmend.IsEnabled = false;
            textBox3Amend.IsEnabled = false;
            Astatus.IsEnabled = false;
            studentIDTxtAmend.Text = "";
            fNameTxtAmend.Text = "";
            mNameTxtAmend.Text = "";
            surnameTxtAmend.Text = "";
            courseBoxAmend.SelectedIndex = 0;
            textBox4Amend.Text = "";
            textBox5Amend.Text = "";
            emailTxtAmend.Text = "";
            ttLine1TxtAmend.Text = "";
            ttLine2TxtAmend.Text = "";
            ttCityTxtAmend.Text = "";
            postcodeTxtAmend.Text = "";
            nttLine1TxtAmend.Text = "";
            textBox2Amend.Text = "";
            textBoxAmend.Text = "";
            textBox3Amend.Text = "";
            Astatus.SelectedIndex = 0;
        }

        private void Acancel_Click(object sender, RoutedEventArgs e)
        {
            disableAmend();
        }

        private async void Asave_Click(object sender, RoutedEventArgs e)
        {
            Asave.Content = "Saving...";
            Asave.IsEnabled = false;
            Student s = new Student();
            s.ID = studentIDTxtAmend.Text;
            s.FirstName = fNameTxtAmend.Text;
            s.MiddleName = mNameTxtAmend.Text;
            s.LastName = surnameTxtAmend.Text;
            s.CourseID = int.Parse(courseBoxAmend.SelectedValue.ToString());
            s.HomePhone = textBox4Amend.Text;
            s.MobilePhone = textBox5Amend.Text;
            s.EmailPersonal = emailTxtAmend.Text;
            s.tLine1 = ttLine1TxtAmend.Text;
            s.tLine2 = ttLine2TxtAmend.Text;
            s.tCity = ttCityTxtAmend.Text;
            s.tPostCode = postcodeTxtAmend.Text;
            s.hLine1 = nttLine1TxtAmend.Text;
            s.hLine2 = textBox2Amend.Text;
            s.hCity = textBoxAmend.Text;
            s.hPostCode = textBox3Amend.Text;
            s.DOB = dobTxtAmend.Text;
            if (Astatus.SelectedIndex == 0)
            {
                s.Status = "Provisional";
            }
            else if (Astatus.SelectedIndex == 1)
            {
                s.Status = "Live";
            }
            else if (Astatus.SelectedIndex == 2)
            {
                s.Status = "Dormant";
            }
            await s.amend();
            disableAmend();
            Asave.Content = "Save";
            Asave.IsEnabled = true;

        }
    }
}